import Vue from 'vue'
import pageJson from "@/pages.json"
export default {
	data() {
		return {
			// 默认的全局分享内容（待测试）
			share: {
				title: '分享标题',
				path: '/pages/index/index', // 全局分享的路径
				imageUrl: '', // 全局分享的图片(可本地可网络)
			}
		}
	},
	onLoad() {
		uni.showShareMenu({
			withShareTicket: true,
			menus: ["shareAppMessage", "shareTimeline"]
		})
	},

	// 定义全局分享
	// 1.发送给朋友
	onShareAppMessage(res) {
		let pages = getCurrentPages(); //获取当前页面栈的信息
		let currentPage = pages[pages.length - 1]; //获取到当前页面栈中最后一个页面的索引
		let obj = {}
		pageJson.pages.forEach(item => {
			if (item.path == currentPage.route) {
				obj = item
			}
		})
		pageJson.subPackages.forEach(item => {
			item.pages.forEach(val => {
				if (currentPage.route.includes(val.path)) {
					obj = val
					obj.path = `${item.root}/${val.path}`
				}
			})
		})
		console.log(obj, "obj")
		let path = ""
		if (currentPage.options) {
			path = '/'+obj.path+ '?'+this.objectToQueryString(currentPage.options)
		}
		let title=obj.style.navigationBarTitleText?obj.style.navigationBarTitleText:'校品园品'
		
		return {
			title,
			path
			// imageUrl: this.share.imageUrl,
		}
	},
	//2.分享到朋友圈
	onShareTimeline(res) {
		let pages = getCurrentPages(); //获取当前页面栈的信息
		let currentPage = pages[pages.length - 1]; //获取到当前页面栈中最后一个页面的索引
		let obj = {}
		pageJson.pages.forEach(item => {
			if (item.path == currentPage.route) {
				obj = item
			}
		})
		pageJson.subPackages.forEach(item => {
			item.pages.forEach(val => {
				if (currentPage.route.includes(val.path)) {
					obj = val
					obj.path = `${item.root}/${val.path}`
				}
			})
		})
		console.log(obj, "obj")
		
		let title=obj.style.navigationBarTitleText?obj.style.navigationBarTitleText:'校品园品'
		let query=this.objectToQueryString(currentPage.options)
		console.log(query,"queryquery")
		// 判断是否是课程详情的分享
		return {
			title,
			query
			// imageUrl: this.share.imageUrl,
		}
		
	},
	methods: {
		
		// 对象转字符串&拼接 朋友圈query处理
		objectToQueryString(obj) {
		  const parts = [];
		  
		  // 遍历对象属性
		  for (const key in obj) {
		    if (obj.hasOwnProperty(key)) {
		      // 将属性名和属性值编码后添加到数组
		      parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
		    }
		  }
		  
		  // 用 & 连接所有部分
		  return parts.join('&');
		},
		
	}
}